/*
 * @Date: 2022-12-26 14:26:05
 * @LastEditors: 旧轩00°°
 * @LastEditTime: 2022-12-30 14:59:06
 * @FilePath: /vue3-ts-vite-pinia-husky/src/stores/user.ts
 */
import { ref } from 'vue'
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import * as api from '@/api/user'
import { cache } from '@/utils'
import { defaultSetting } from '@/config/setting'
import { filterRecursionRoutes, setDefaultRoute } from '@/utils/handleRoutes'
import router, { allRoutes, asyncRoutes } from '@/router'

const { TOKEN, USER_INFO, USER_MENU } = defaultSetting

//
function hasPermission(dyRoutes: any) {
  let _asyncRoutes = setDefaultRoute(dyRoutes, '/main')
  const routes = filterRecursionRoutes(_asyncRoutes, allRoutes)
  routes.forEach((route) => router.addRoute('main', route))
  return routes
}

export const useUserStore = defineStore('user', () => {
  const userInfo = ref({})
  const userMenus = ref([])
  const token = ref('')

  // 登录并获取用户信息
  const requestApiLogin = async (params) => {
    // 1.登录
    const { id, token } = await api.login(params)
    cache.setCache(defaultSetting.TOKEN, token)
    ElMessage.success('登录成功')

    // 2.获取用户详细信息
    const userInfo = await api.userInfoById(id)
    cache.setCache(defaultSetting.USER_INFO, userInfo)

    // 3.根据用户的角色请求用户的权限 接口返回的
    // const roleMenus = await api.roleIdMenu(userInfo.role.id)

    // *** 添加动态路由 ***
    userMenus.value = hasPermission(asyncRoutes)
    cache.setCache(USER_MENU, userMenus.value)
  }

  // 用户进行刷新默认加载数据
  const localLocalCache = async () => {
    token.value = cache.getCache(TOKEN)
    userInfo.value = cache.getCache(USER_INFO)
    userMenus.value = cache.getCache(USER_MENU)
    if (token.value && userInfo.value && userMenus.value) {
      userMenus.value = hasPermission(asyncRoutes)
    }
  }

  return { userInfo, userMenus, requestApiLogin, localLocalCache }
})
